package com.qyhl.module_activities.act;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.module_activities.R;
import com.qyhl.module_activities.R2;
import com.qyhl.module_activities.common.ActivityConstant;
import com.qyhl.module_activities.utils.inter.RecycleViewDivider;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.act.ActivityListTempBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;

/**
 * 活动列表
 * 2018-01-10
 *
 * @author helin
 */
public class ActivityTempFragment extends BaseFragment implements ActivityTempContract.ActivityTempView {

    /**
     * 布局文件
     */
    private View mRootView;


    @BindView(R2.id.recyclerView)
    RecyclerView mRecyclerView;
    /**
     * 下拉刷新控件
     */
    @BindView(R2.id.act_refresh)
    SmartRefreshLayout mActResresh;

    /**
     * 标题
     */
    @BindView(R2.id.title)
    TextView mTitle;
    /**
     * 标题
     */
    @BindView(R2.id.titlelayout)
    RelativeLayout titlelayout;

    @BindView(R2.id.load_mask)
    LoadingLayout mLoadingLayout;
    @BindView(R2.id.title_left)
    ImageView title_left;

    private ActivityTempContract.ActivityTempPresenter mPresenter;
    private List<ActivityListTempBean> mActivityData = new ArrayList<>();
    /**
     * 最后一条活动ID
     */
    private int lastId = 0;
    //列表类型
    private int type = 0;
    private CommonAdapter<ActivityListTempBean> mAdapter;
    private String title;

    public ActivityTempFragment() {
    }

    /**
     * @return A new instance of fragment ActivityTempFragment.
     */
    public static ActivityTempFragment newInstance(String title, boolean isback, int type) {
        ActivityTempFragment fragment = new ActivityTempFragment();
        Bundle args = new Bundle();
        args.putString("title", title);
        args.putBoolean("isback", isback);
        args.putInt("type", type);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return mRootView = inflater.inflate(R.layout.act_fragment_activity_temp, container, false);
    }

    @Override
    protected void create() {
        mPresenter = new ActivityTempPresenter(ActivityTempFragment.this);

        initView();
        loadData();
    }

    @Override
    public void initImmersionBar() {
        if (!StringUtils.isEmpty(title)) {
            ImmersionBar.with(this)
                    .statusBarColor(R.color.white)
                    .statusBarDarkFont(true)
                    .fitsSystemWindows(true)
                    .init();
        }
    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void onFirstVisible() {
//        loadData();
    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }


    /**
     * 初始化View
     */
    private void initView() {
        type = getArguments().getInt("type");
        mLoadingLayout.setStatus(LoadingLayout.Loading);
        title = getArguments().getString("title");
        if (TextUtils.isEmpty(title)) {
            titlelayout.setVisibility(View.GONE);
        } else {
            if (getArguments().getBoolean("isback", false)) {
                title_left.setVisibility(View.VISIBLE);
                title_left.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getActivity().finish();
                    }
                });
            }

            mTitle.setText(title);
        }

        mActResresh.setEnableLoadMore(true);
        //刷新中禁止操作
        mActResresh.setDisableContentWhenRefresh(true);
        mActResresh.setRefreshHeader(new MaterialHeader(mContent));
        mActResresh.setRefreshFooter(new ClassicsFooter(mContent));
        //下拉加载
        mActResresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                lastId = 0;
                mPresenter.getData(lastId, type);
            }
        });

        //加载更多
        mActResresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                lastId = mActivityData.get(mActivityData.size() - 1).getActivity().getId();
                mPresenter.getData(lastId, type);
            }
        });
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContent));
        mRecyclerView.addItemDecoration(new RecycleViewDivider(
                getActivity(), LinearLayoutManager.VERTICAL, 10, ContextCompat.getColor(getActivity(), R.color.global_background)));
        mRecyclerView.setAdapter(mAdapter = new CommonAdapter<ActivityListTempBean>(mContent, R.layout.act_item_act_list, mActivityData) {

            @Override
            protected void convert(ViewHolder holder, ActivityListTempBean activityListTempBean, int position) {
                ImageView status = holder.getView(R.id.activity_status);
                setSpannableString(activityListTempBean, status);
                RoundedImageView bg = holder.getView(R.id.bg_image);
                Glide.with(mContent)
                        .load(activityListTempBean.getActivity().getPosterUrl())
                        .into(bg);
                holder.setText(R.id.act_title, activityListTempBean.getActivity().getActName());
                if (TextUtils.isEmpty(activityListTempBean.getActivity().getDigest())) {
                    holder.setVisible(R.id.act_digest, false);
                } else {
                    holder.setVisible(R.id.act_digest, true);
                    holder.setText(R.id.act_digest, activityListTempBean.getActivity().getDigest());
                }
                Long pageNumber = activityListTempBean.getActivity().getPageViews();
                holder.setText(R.id.act_number, pageNumber == null ? "0阅" : (pageNumber + "阅"));
                holder.setText(R.id.end_time, "活动时间: " +
                        parseDate(activityListTempBean.getActivity().getStartTime()) + "-" +
                        parseDate(activityListTempBean.getActivity().getEndTime()));
            }
        });
        /**
         * 列表点击事件
         */
        mAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, final int position) {
                ActivityListTempBean act = mActivityData.get(position);
                int actId = act.getActivity().getId();
                Bundle bundle = new Bundle();
                bundle.putString("actId", actId + "");

                RouterManager.router(ARouterPathConstant.ACT_DETAILS, bundle);

                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.ACTIVITY_LIST, ActionConstant.ACTIVITY_DETAIL);

                if (type == 2) {
                    //报名活动
                    ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.MY_SIGNUP_ACT, ActionConstant.ACTIVITY_DETAIL);
                } else {
                    //收藏活动
                    ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.MY_COLLECTION_ACT, ActionConstant.ACTIVITY_DETAIL);
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        mLoadingLayout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View view) {
                lastId = 0;
                mPresenter.getData(lastId, type);
                mLoadingLayout.setStatus(LoadingLayout.Loading);
            }
        });
    }

    /**
     * 时间转换
     */
    public String parseDate(String dateStr) {
        try {
            //"yyyy-MM-dd HH:mm:ss" 完整
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
            Date date = sdf.parse(dateStr);
            //"MM/dd HH:mm" 转换
            sdf.applyPattern("MM.dd HH:mm");
            return sdf.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dateStr;
    }

    /**
     * 活动状态
     */
    private void setSpannableString(ActivityListTempBean activityListTempBean, ImageView status) {
        //活动状态
        int actStatus = activityListTempBean.getActStatus();
        //选手状态
        int applyStatus = activityListTempBean.getApplyStatus();
        //投票状态
        int voteStatus = activityListTempBean.getVoteStatus();

        if (actStatus == ActivityConstant.STATUS_PROCESSING) {
            if (applyStatus == ActivityConstant.SING_UP_ON) {
                //报名中
                status.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.img_status_singup));
            } else if (voteStatus == ActivityConstant.VOTE_ON) {
                //投票中
                status.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.img_status_voteon));
            } else {
                //进行中
                status.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.img_status_processing));
            }
        } else if (actStatus == ActivityConstant.STATUS_END) {
            //已结束
            status.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.img_status_end));
        }
    }


    /**
     * 加载数据
     */
    private void loadData() {
        mPresenter.getData(lastId, type);
    }


    @Override
    public void onError(String message) {
        mActResresh.finishRefresh();
        if (lastId == 0) {
            errorLoad(message, mLoadingLayout);
        } else {
            showToast(message, ERROR);
        }
    }

    @Override
    public void onSuccess(List<ActivityListTempBean> data) {
        mActResresh.finishRefresh();
        mActResresh.finishLoadMore();
        mLoadingLayout.setStatus(LoadingLayout.Success);
        if (data == null || data.size() == 0) {
            if (lastId == 0) {
                emptyLoad(mLoadingLayout);
            } else {
                showToast("没有更多啦！", INFO);
            }
            return;
        }

        if (lastId == 0) {
            if (data.size() < 10) {
                mActResresh.setEnableLoadMore(false);
            }
            mActivityData.clear();
        }
        mActivityData.addAll(data);
        mAdapter.notifyDataSetChanged();
    }


}
